package app.sso.demo;

import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.sso.exception.UserException;
import com.authine.cloudpivot.web.sso.security.BaseAuthenticationToken;
import com.authine.cloudpivot.web.sso.template.BaseSimpleTemplate;
import com.authine.cloudpivot.web.sso.template.ResponseTypeEnum;
import com.authine.cloudpivot.web.sso.template.SimpleTemplateConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 前端 xxxx/login/SSOLogin?code=username_md5加密信息
 */
@Component
@Slf4j
public class SSOLogin extends BaseSimpleTemplate {

    @Autowired
    CloudSqlService sqlService;

    SSOLogin() {
        super(SimpleTemplateConfig.builder()
                .requestMatcher(new AntPathRequestMatcher("/login/SSOLoginByEmployeeNO", HttpMethod.GET.name()))
                .responseType(ResponseTypeEnum.JSON)
                .redirectClientID("api")
                .build());
    }

    protected SSOLogin(SimpleTemplateConfig config) {
        super(config);
    }

    @Override
    public String getSourceId(BaseAuthenticationToken token) {
        String code = token.getCode();
        StringBuffer selectSql = new StringBuffer("select * from h_org_user where employeeNO = '").append(code).append("'order by createdTime limit 1");
        Map<String, Object> map = sqlService.getMap(selectSql.toString());
        String employeeNO = MapUtils.getString(map, "employeeNO");
        String username = MapUtils.getString(map, "username");
        if (StringUtils.isBlank(employeeNO)) {
            throw new UserException("无法员工编码查询到用户");
        }
        return username;
    }

    @Override
    public UserModel getUser(Object username) {
        if (username == null) {
            log.info("code为空");
            return null;
        } else {
            //根据用户名查询
            log.info("code == " + username);
            return engineService.getSystemSecurityFacade().getUserByUsername(String.valueOf(username));
        }
    }

}
